package com.zsc.roadsys.controller.admin;


import com.github.pagehelper.PageInfo;
import com.zsc.roadsys.bean.ResponseBean;
import com.zsc.roadsys.controller.BaseController;
import com.zsc.roadsys.domain.PageDomain;
import com.zsc.roadsys.dto.UserDto;
import com.zsc.roadsys.entity.User;
import com.zsc.roadsys.exception.UserDeleteException;
import com.zsc.roadsys.exception.UserNotFoundException;
import com.zsc.roadsys.service.UserService;
import com.zsc.roadsys.utils.StringFormmat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/admin/user")
@Slf4j
public class UserController extends BaseController{
    String prefix = "admin/user";

    @Autowired
    UserService userService;

    /**分页查询用户*/
    @GetMapping("/list")
    public ResponseBean listTicket(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "id") String sortColumn,
            @RequestParam(defaultValue = "asc") String sortOrder,
            User user)
    {
        log.info("分页请求" + pageNum + ";" + pageSize + sortColumn);
        //将前端的字段字符串转换为下划线格式，并构造分页对象
        PageDomain pageDomain = new PageDomain(pageNum, pageSize,
                StringFormmat.toUnderScore(sortColumn), sortOrder);
        PageInfo<User> pageInfo = userService.listUser(pageDomain, user);
        return ResponseBean.success(pageInfo);
    }

    /**展示用户详情*/
    @GetMapping("/{id}")
    public ModelAndView view(@PathVariable Long id) {
        log.info("读取用户信息，id = " + id);
        User user = userService.getUserById(id);
        if (user == null) {
            throw new UserNotFoundException();
        }
        return new ModelAndView(prefix+"/view","user",user);
    }

    /**删除用户*/
    @DeleteMapping("/{id}")
    public ResponseBean delete(@PathVariable("id") long id) {
        if (!userService.deleteUser(id)) {
            throw new UserDeleteException();
        }
        return ResponseBean.success();

    }

    /**更新用户*/
    @PutMapping("")
    public ResponseBean update(UserDto user) {
        System.out.println(user);
        userService.updateUser(user);
        return ResponseBean.success();
    }

    /**这里还可以有更换密码，更新激活状态功能，敬请期待！*/
}
